package api

import (
	"cr.org/constant"
	"cr.org/model"
	"cr.org/modules/service"
	"cr.org/utils"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
	"net/url"
	"time"
)

type userApi struct{}

func (api userApi) AddUser(c *gin.Context) {
	var arg model.AddUser
	if err := c.ShouldBindJSON(&arg); err != nil {
		log.Error(err)
		BadWithCode(c, constant.ParamsError)
		return
	}
	err := service.UserService.AddUser(arg)
	if err != nil {
		log.Error(err)
		BadWithError(c, err)
		return
	}
	Ok204(c)
}

func (api userApi) Login(c *gin.Context) {
	var loginAccount model.LoginAccount
	if err := c.ShouldBindJSON(&loginAccount); err != nil {
		log.Error(err)
		BadWithCode(c, constant.ParamsError)
		return
	}
	if !service.UserService.VerifyCode(loginAccount.VeryCode) {
		BadWithCode(c, constant.VerifyCodeErr)
		return
	}
	result, bInfo, err := service.UserService.UserLogin(loginAccount)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"success": false, "data": err.Error()})
		return
	}
	api.setCookie(c.Writer, bInfo)
	Ok(c, gin.H{"success": true, "data": result})
}

// 设置 cookie 的工具方法
func (api userApi) setCookie(r http.ResponseWriter, baseInfo utils.BaseClaims) {
	cv := utils.MD5(baseInfo.Username)
	http.SetCookie(r, &http.Cookie{
		Name:     constant.CookieKey,
		Value:    url.QueryEscape(cv),
		Path:     "/",
		Domain:   "",
		Expires:  time.Now().Add(time.Duration(constant.JWTAccessTime)).UTC(),
		MaxAge:   constant.JWTAccessTime,
		Secure:   false,
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
	})
}

// 移除 cookie 的工具方法
func (api userApi) removeCookie(r http.ResponseWriter) {
	http.SetCookie(r, &http.Cookie{
		Name:     constant.CookieKey,
		Value:    "",
		Path:     "/",
		Domain:   "",
		Secure:   false,
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
	})
}

func (api userApi) Logout(c *gin.Context) {
	api.removeCookie(c.Writer)
}
